//
//  JieXiaoDetailController.swift
//  HappyEat
//
//  Created by ctx2016 on 17/1/17.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SwiftyJSON

class JieXiaoDetailController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    
    let JieXiaoCellId:String = "JieXiaoCELLID"
    
    let jiexiaoSecTion1:String = "jiexiaoCellSection1"
    
    let mineSetSwitchCellId:String = "MineSetSwitchCellID"
    
    let joinStyle:String = "JiexiaoJoinStyleCellID"
    
    var tableview:UITableView = UITableView.init()
    
    var titleNames:[String] = ["参与方式","商家店铺","往期回顾","抢宝晒单","本期参与记录"]
    
    var timeStr:String = "2017-1-29 09:00:00"
    
    var netRequst = NetworkRequest.shareInstance
    
    var model:HomePageProductModel?
    //详情Modle
    var detailModel:ProductDetailModel?
    
    //倒计时类
    var countDown:CountDown?
    
    let headerView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: k_Wide, height: 240))
    
    let bottomView:JieXiaoDetailBottomView = JieXiaoDetailBottomView.init(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
        self.startCountDown()//计时器
        self.loadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setNav()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.subviews.first?.alpha = 1.0
    }
}
extension JieXiaoDetailController{
    func setNav(){
        self.navigationItem.title = "商品详情"
        self.navigationController?.navigationBar.subviews.first?.alpha = 0.0
        UIApplication.shared.setStatusBarStyle(.default, animated: true)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_back", fontSize: 14, target: self, action: #selector(leftButtonAction))
    }
    func leftButtonAction(){
        self.navigationController!.popViewController(animated: true)
    }
    func setUI(){
        self.view.addSubview(self.tableview)
        self.tableview.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(20)
            make.bottom.equalTo(-49)
        }
        self.tableview.delegate = self
        self.tableview.dataSource = self
        self.tableview.separatorStyle = .none
        self.tableview.register(JieXiaoDetailCell.self , forCellReuseIdentifier: JieXiaoCellId)
        self.tableview.register(JieXiaoSecTion1Cell.self, forCellReuseIdentifier: jiexiaoSecTion1)
        self.tableview.register(MineSetSwitchCell.self, forCellReuseIdentifier: mineSetSwitchCellId)
        self.tableview.register(JiexiaoJoinStyleCell.self, forCellReuseIdentifier: joinStyle)
        self.tableview.mj_footer = JieXiaoDetailFooter.init(refreshingTarget: self, refreshingAction: #selector(seeDetailEventAction))
        tableview.separatorStyle = .none
        //当隐藏显示navi的时候设置为no时布局是以(0,0,0,0)开始的
        self.automaticallyAdjustsScrollViewInsets = false
        self.tableview.tableHeaderView = self.headerView
        self.headerView.backgroundColor = .red
        self.view.addSubview(self.bottomView)
        self.bottomView.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(49)
            make.bottom.equalTo(0)
        }
        self.bottomView.leftButton.addTarget(self, action: #selector(buttonViewLeftButtonAction), for: .touchUpInside)
        self.bottomView.rightButton.addTarget(self, action: #selector(buttonViewRightButtonAction), for: .touchUpInside)
    }
    //MARK:GetData
    func loadData(){
        var userId:String? = UserDefaults.standard.object(forKey: ID) as? String
        if userId == nil{
           userId = ""
        }
        let paramsDic:[String:String] = ["productSeriesId":(self.model?.productSeriesId)!,
                                         "userId":userId!]
        self.netRequst.postRequest(urlString: GetProductDetail_URL, params: paramsDic, success: { (success) in
            print(success)
            let JsonDic = JSON(success)
            if JsonDic["status"] == "SUCCESS" {
                //结果正确
                self.detailModel = ProductDetailModel.init(data: JsonDic["data"])
                print((self.detailModel?.status)!)
                print(self.detailModel?.progress!)
                self.tableview.reloadData()
            }
        })
        { (error) in
            print(error)
        }
    }
    //MARK:getNowTimeWithString
    func getNowTimeWithString(_ atimeStrig:String)->String{
        let formate:DateFormatter =  DateFormatter.init()
        formate.dateFormat = "yyyy-MM-dd HH:mm:ss"
        //截止时间date格式
        let expireDate:Date = formate.date(from: atimeStrig)!
        var nowDate:Date = Date.init()
        //当前时间字符串格式
        let nowDateStr:String = formate.string(from: nowDate)
        //当前时间格式
        nowDate = formate.date(from: nowDateStr)!
        let timeInterVal:Double = expireDate.timeIntervalSinceNow
        
        let days:Int = Int(timeInterVal/(3600*24))
        let hours = Int(timeInterVal/3600)
        let minus = Int(((timeInterVal -  Double(hours*3600))/60))
        let seconds = Int(timeInterVal - Double(hours * 3600) - Double(minus * 60))
        
        var dayStr:String = String(days)
        var hourStr:String = String(hours)
        var minusStr:String = String(minus)
        var secondStr:String = String(seconds)
        if hours < 10{
            hourStr = "0"+hourStr
        }
        if minus < 10 {
            minusStr = "0" + minusStr
        }
        if seconds < 10 {
            secondStr = "0" + secondStr
        }
        if (hours <= 0)&&(minus <= 0)&&(seconds <= 0){
            return "00:00:00"
        }
        return hourStr+":"+minusStr+":"+secondStr
    }
    //MARK:LoadData(){
    func startCountDown(){
        self.countDown = CountDown.init()
        self.countDown?.countDown(per_SECBlock: {
            let timeLabel:UILabel = self.view.viewWithTag(10000) as! UILabel
            timeLabel.text = self.getNowTimeWithString(self.timeStr)
        })
    }
    //MARK:seeDetailEvent
    func seeDetailEventAction(){
        self.perform(#selector(hidefootFresh), with: self, afterDelay: 3)
    }
    func hidefootFresh(){
        self.tableview.mj_footer.endRefreshing()
    }
    //MARK:底部视图的参加按钮和全家兑换按钮的点击事件
    func buttonViewLeftButtonAction(){
        //左边按钮
        let vc:JieXiaoDingdanDetail = JieXiaoDingdanDetail()
        vc.detaiModel = self.detailModel
        self.navigationController!.pushViewController(vc, animated: true)
    }
    func buttonViewRightButtonAction(){
        //右边按钮
        
    }
    @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("Selected")
    }
    @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return 1
        case 2:
            return 1
        default:
            return self.titleNames.count
        }
    }
    @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            let label:UILabel = UILabel.init()
            let titleLabelHeight:CGFloat = label.jqGetHeightWithstr(self.model?.productName, withfontSize: 16, withLineSpace: 0, withmaxWidth: k_Wide - 32)
            return 16+8+12+8+14+10+12 - 16 + titleLabelHeight
        case 1:
            return 12+20+24+80+16.5
        case 2:
            return 97
        default:
            return 50
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 0.001
        case 1:
            return 0.001
        case 2:
            return 4
        default:
            return 0.001
        }
    }
    @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell:JieXiaoDetailCell = tableView.dequeueReusableCell(withIdentifier: JieXiaoCellId) as! JieXiaoDetailCell
//            (cell ).addNameLabel.text = "湘泸小馆(百大店)"
//            (cell ).nameLabel.text = "芝士蛋糕"
//            (cell ).tagLabel.text = "进行中"
//            (cell ).qhLabel.text = "期号:312145
            cell.detailModel = self.detailModel
            return cell
        case 1:
            let cell:JieXiaoSecTion1Cell = tableView.dequeueReusableCell(withIdentifier: jiexiaoSecTion1) as! JieXiaoSecTion1Cell
            cell.progressView.progress = 0.6
            cell.needLabel.text = "总需要\(self.detailModel?.needPerson ?? "")人次"
            cell.tagLabel.text = "人数已经满了"
            cell.tagJiexiaoLabel.text = "揭晓倒计时"
            cell.djsLabel.text = self.getNowTimeWithString(self.timeStr)
            cell.djsLabel.tag = 10000
            cell.mineJoinLabel.text = "您没有参与本期的夺宝奥"
//            cell.cellType = .unJoinType
            cell.cellType = .zhongchouType
            cell.detailModel = self.detailModel
            self.startCountDown()
            return cell
        case 2:
            let cell:JiexiaoJoinStyleCell = tableView.dequeueReusableCell(withIdentifier: joinStyle) as!JiexiaoJoinStyleCell
            return cell
        default:
//            let cell:MineSetSwitchCell = MineSetSwitchCell.init(style: .default, reuserIdentify: mineSetSwitchCellId, cellStyle: .rightAllStyle)
             let cell:MineSetSwitchCell = tableView.dequeueReusableCell(withIdentifier: mineSetSwitchCellId) as! MineSetSwitchCell
            cell.cellStyle = .rightAllStyle
            cell.leftLabel.text = self.titleNames[indexPath.row]
            return cell
        }
    }
}
